import { useEffect, useState } from 'react'
import { useLocation, Link } from 'react-router-dom'
import { MenuList } from './model'
import { useSelector } from 'react-redux'
import { Breadcrumb } from 'antd'

function gerenateBreadcrumb(
  menuList: MenuList[],
  pathname: string,
  result: any[]
) {
  menuList.forEach((item: MenuList) => {
    if (pathname.indexOf(item.key) > -1) {
      const temp = {
        key: item.key,
        title: item.label,
        current: item.key === pathname
      }
      result.push(temp)
      if (item.children) {
        gerenateBreadcrumb(item.children, pathname, result)
      }
    }
  })
  return result
}
function BreadcrumbNav() {
  const { menuList } = useSelector((state: any) => state.authSlice)
  const [breadList, setBreadList] = useState<any[]>([])
  const location = useLocation()

  useEffect(() => {
    // 将 location 的 pathname 与菜单进行匹配, 获取响应的 label 和 path
    const result = gerenateBreadcrumb(menuList, location.pathname, [])
    setBreadList(result)
  }, [location, menuList])

  // 对 返回的结果进行遍历, 判断是否是第一个和最后一个, 第一个和最后一个都不能点击跳转
  return (
    <Breadcrumb>
      {breadList.map((item, index) => {
        const isLast = index === breadList.length - 1 || index === 0
        return (
          <Breadcrumb.Item key={item.key}>
            {isLast ? item.title : <Link to={item.key}>{item.title}</Link>}
          </Breadcrumb.Item>
        )
      })}
    </Breadcrumb>
  )
}

export default BreadcrumbNav
